﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;

namespace WebProxyApplication.Certificate
{
    public class ProxyCertVerifier
    {

        //public SslPolicyErrors SslPolicyErrors { get; set; }

        public static bool ValidateServerCertficate(
            object sender,
            X509Certificate certificate,
            X509Chain chain,
            SslPolicyErrors sslPolicyErrors)
        {
            ProxyLogger.Log.DebugFormat("SSL certificate error {0} from {1} with name {2}", sslPolicyErrors, certificate.Issuer, certificate.Subject);

            //SslPolicyErrors = sslPolicyErrors;

            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                // Good certificate.
                return true;
            }

            //// If there are errors in the certificate chain, look at each error to determine the cause.
            //if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0)
            //{
            //    if (chain != null && chain.ChainStatus != null)
            //    {
            //        foreach (X509ChainStatus status in chain.ChainStatus)
            //        {
            //            if ((certificate.Subject == certificate.Issuer) &&
            //               (status.Status == X509ChainStatusFlags.UntrustedRoot))
            //            {
            //                // Self-signed certificates with an untrusted root are valid. 
            //                continue;
            //            }
            //            else
            //            {
            //                if (status.Status != X509ChainStatusFlags.NoError)
            //                {
            //                    // If there are any other errors in the certificate chain, the certificate is invalid,
            //                    // so the method returns false.
            //                    return false;
            //                }
            //            }
            //        }
            //    }

            //    // When processing reaches this line, the only errors in the certificate chain are 
            //    // untrusted root errors for self-signed certificates. These certificates are valid
            //    // for default Exchange server installations, so return true.
            //    return true;
            //}
            else
            {
                // In all other cases, return false.
                return false;
            }
        }
    }
}